package com.cksys.achievement.config.login.qq;

import com.cksys.achievement.exception.NoBindingException;
import com.cksys.achievement.exception.ValidateCodeException;
import com.cksys.achievement.service.impl.CustomUserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: QQAuthenticationSuccessHandler
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2020/4/16 17:31
 */
@Slf4j
public class QQAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String result = "{\"payload\":\"%s\",\"success\":false,\"msg\":\"%s\",\"code\":200}";
        PrintWriter out = null;
        response.setContentType("application/json;charset=utf-8");
        try {
            out = response.getWriter();

            if (exception instanceof ValidateCodeException) {
                String message = exception.getMessage();
                result = String.format(result, message, message);
            }

            if (exception instanceof NoBindingException) {
                String message = exception.getMessage();
                result = String.format(result, message, message);
            }

        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            out.write(result);
            out.flush();
            out.close();
        }
    }

}
